package com.proj.hot.utils;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


public class DownloadFileUtil {
	private static OnDownloadListener listener;
	public static void downloadFile(final String urlString) {
//		final String urlString="http://dldir1.qq.com/weixin/android/weixin6315android760.apk";

		if (TextUtils.isEmpty(urlString)) {
			return;
		}
		final String fileName = urlString.substring(urlString.lastIndexOf("/"));
		final String saveDir = "/data/data/cn.gd.snm.snmcm/"+fileName;
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (!Thread.currentThread().isInterrupted()) {
					switch (msg.what) {
					case -1:
						listener.onDownloadFail(urlString);
						break;
					case 0:
						listener.onDownloading(urlString, msg.arg1, msg.arg2);
						break;
					case 1:
						listener.onDownloadSuccess(urlString, saveDir+"/"+fileName);
						break;

					default:
						break;
					}
				}
			}

		};
		
		new Thread(){
			public void run() {
				startDownloadFile(urlString, saveDir,fileName,handler);
			};
		}.start();
	}

	private static void startDownloadFile(String urlString, String saveDir,String fileName,Handler handler) {
		URLConnection connection = null;
		InputStream inputStream = null;
		
		
		/*
		 * 连接到服务器
		 */
		try {
			URL url = new URL(urlString);
			connection = url.openConnection();
			if (connection.getReadTimeout() == 5) {

			}
			inputStream = connection.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Message message = new Message();
		if (connection==null||inputStream==null) {
			message.what = -1;
			handler.sendMessage(message);
			return;
		}
		
		/*
		 * 文件的保存路径和和文件名其中Nobody.mp3是在手机SD卡上要保存的路径，如果不存在则新建
		 */
		File file1 = new File(saveDir);
		if (!file1.exists()) {
			file1.mkdir();
		}
		String savePathString = "sdcard" + "/"+fileName;
		
		File file = new File(savePathString);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (file==null||!file.exists()) {
			message.what = -1;
			handler.sendMessage(message);
			return;
		}
		
		
		OutputStream outputStream = null;
		/*
		 * 向SD卡中写入文件
		 */
		try {
			handler.sendEmptyMessage(0);
			outputStream = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 4];
			int fileLength = connection.getContentLength();
			message.arg2 = fileLength;
			int downedFileLength = 0;
			message.what = 0;
			int len = 0;
			while ((len=inputStream.read(buffer))!=-1) {
				outputStream.write(buffer);
				downedFileLength += len;

				//message.arg2 = downedFileLength;
				Message msg=handler.obtainMessage(0, fileLength, downedFileLength);
				handler.sendMessage(msg);
			}
			message.what = 1;
			handler.sendMessage(message);
		} catch (Exception e) {
			e.printStackTrace();
			message.what = -1;
			handler.sendMessage(message);
		} 
		if (outputStream!=null) {
			try {
				outputStream.close();
			} catch (IOException e) {
			}
		}
		if (inputStream!=null) {
			try {
				inputStream.close();
			} catch (IOException e) {
			}
		}
	}
	
	
	public static void setOnDownloadListener(OnDownloadListener onDownloadListener){
		listener=onDownloadListener;
	}
	public interface OnDownloadListener{
		void onDownloadFail(String url);
		void onDownloading(String url, int fileSize, int downedFileLength);
		void onDownloadSuccess(String url, String path);
	}
}
